﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Configuration;

namespace QuanLyKho
{
    public partial class Config : Form
    {
        private static bool _flag;
        public Config()
        {
            InitializeComponent();
            _flag = true;
            LoadConfig();
        }
        private void bntThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void bntLuuLai_Click(object sender, EventArgs e)
        {
            ReLoadConfig();
        }

        private void LoadConfig()
        {
            try
            {
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "QuanLyKho.exe.config");
                var xmlFile = XDocument.Load(path);

                var query = from c in xmlFile.Elements("configuration").Elements("connectionStrings")
                            select c;

                string data = String.Empty;
                foreach (XElement item in query)
                {
                    data = item.Element("add").Attribute("connectionString").Value;
                }

                var temp = data.Split(';');
                if (temp.Length == 4)
                {
                    txtServer.Text = temp[0].Split('=')[1];
                    txtDatabase.Text = temp[1].Split('=')[1];
                    txtLogin.Text = temp[2].Split('=')[1];
                    txtPassword.Text = temp[3].Split('=')[1];
                }
                else if (temp.Length == 5)
                {
                    try
                    {
                        txtServer.Text = temp[0].Split('=')[1];
                        txtDatabase.Text = temp[1].Split('=')[1];
                        txtLogin.Text = temp[3].Split('=')[1];
                        txtPassword.Text = temp[4].Split('=')[1];
                    }
                    catch (IndexOutOfRangeException)
                    {
                        return;
                    }

                }
            }
            catch (Exception)
            {
                return;
            }

        }

        private static bool SaveConfig(string path, string conString)
        {
            try
            {
                var xmlFile = XDocument.Load(path);

                var query = from c in xmlFile.Elements("configuration").Elements("connectionStrings")
                            select c;

                foreach (XElement item in query)
                {
                    item.Element("add").Attribute("connectionString").Value = conString;
                }

                xmlFile.Save(path);
            }
            catch (XmlException)
            {
                return false;
            }
            return true;
        }

        private void ReLoadConfig()
        {
            var serverName = txtServer.Text.Trim();
            var databaseName = txtDatabase.Text.Trim();
            var login = txtLogin.Text.Trim();
            var password = txtPassword.Text.Trim();

            var conString = @"Data Source=" + serverName + ";Initial Catalog=" + databaseName +
                            ";Persist Security Info=True;User ID=" + login + ";Password=" + password;
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "QuanLyKho.exe.config");
            if (SaveConfig(path, conString))
            {
                if (!_flag)
                {
                    ReConfig(conString);
                }
                MessageBox.Show("Config thành công.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Dispose();
            }
            else
            {
                MessageBox.Show("Config Failure .", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void ReConfig(string conString)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.ConnectionStrings.ConnectionStrings["ConnectionStrings"].ConnectionString = conString;

            config.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.Name);
            Properties.Settings.Default.Reload();
        }


    }
}
